package com.atguigu.dga.governance.assessor.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.constant.DgaConstant;
import com.atguigu.dga.governance.assessor.Assessor;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;

/**
 * ClassName: TableLifecycle
 * Package: com.atguigu.dga.governance.assessor.storage
 * Description:
 *
 * @Author:
 * @Create: 2024/3/18 14:49
 * @Version: 1.0
 */
@Component("TABLE_LIFECYCLE")
public class TableLifecycle extends Assessor {
    @Override
    public void checkProblem(AssessParam assessParam, GovernanceAssessDetail governanceAssessDetail) throws ParseException {
        // 取出当前表的生命周期类型 和 声明周期天数 与 指标中参数进行判断
        String metricParamsJson = assessParam.getGovernanceMetric().getMetricParamsJson();
        JSONObject jsonObject = JSON.parseObject(metricParamsJson);
        Integer paramDays = jsonObject.getInteger("days");

        String lifecycleType = assessParam.getTableMetaInfo().getTableMetaInfoExtra().getLifecycleType();
        Long lifecycleDays = assessParam.getTableMetaInfo().getTableMetaInfoExtra().getLifecycleDays();

        if(lifecycleType == null || DgaConstant.LIFECYCLE_TYPE_UNSET.equals(lifecycleType)) {
            // 未设定
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("未设定生命周期类型");
            return;
        }
        // 日分区 直接判断就行，其他已经给了10分
        if(DgaConstant.LIFECYCLE_TYPE_DAY.equals(lifecycleType)) {
            // 分区信息
            String partitionColNameJson = assessParam.getTableMetaInfo().getPartitionColNameJson();
            List<JSONObject> partitionJsonArr = JSON.parseArray(partitionColNameJson, JSONObject.class);

            if(partitionJsonArr == null || partitionJsonArr.size() == 0) {
                governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
                governanceAssessDetail.setAssessProblem("日分区表未设定分区信息");
                return;
            }

            // 声明周期天数
            if(lifecycleDays == null || lifecycleDays == -1L) {
                governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
                governanceAssessDetail.setAssessProblem("日分区表未设定生命周期天数");
                return;
            }

            // 判定周期天数 与 指标中参数进行比较
            if(lifecycleDays > paramDays) {
                governanceAssessDetail.setAssessScore(BigDecimal.valueOf(paramDays * 10 / lifecycleDays ));
                governanceAssessDetail.setAssessProblem("生命周期天数超过建议值");
            }
        }
    }
}
